package com.eci.common.asset.algorithm;

import com.eci.common.util.StringUtils;

import java.util.Properties;

/**
 * twitter的snow-flake算法
 *  
 */
public class SnowFlake {
	
	
	private SnowFlake() {}
	//静态内部类,包含一个静态属性：Singleton
	private static class SingletonInstance {
		private static final SnowFlake INSTANCE = new SnowFlake();
	}
	//对外公有的静态方法，直接返回SingletonInstance.INSTANCE
	public static synchronized SnowFlake getInstance() {
		return SingletonInstance.INSTANCE;
	}

    /**
     *	 起始的时间戳
     */
    private final static long START_STMP = 1577808000000L;
 
    /**
     * 	每一部分占用的位数
     */
    private final static long SEQUENCE_BIT = 12; //序列号占用的位数
    private final static long MACHINE_BIT = 5;   //机器标识占用的位数
    private final static long DATACENTER_BIT = 5;//数据中心占用的位数
 
    /**
     * 	每一部分的最大值
     */
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
 
    /**
     * 	每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
 
    private static long datacenterId;  //数据中心
    private static long machineId;     //机器标识
    private long sequence = 0L; //序列号
    private long lastStmp = -1L;//上一次时间戳

    static {
        Properties properties = System.getProperties();
        long relation_center_id;
        long relation_machine_id;

        //开发环境 或者本地环境
        if ("dev".equals(properties.getProperty("spring.profiles.active"))
                || "local".equals(properties.getProperty("spring.profiles.active"))) {
            relation_center_id = 1L;
            relation_machine_id = 1L;
        } else {
            relation_center_id = getSystemValue("center_id");
            relation_machine_id = getSystemValue("machine_id");
        }

        if (relation_center_id > MAX_DATACENTER_NUM || relation_center_id < 0) {
            throw new IllegalArgumentException("center_id 必须小于等于31大于0");
        }

        if (relation_machine_id > MAX_MACHINE_NUM || relation_machine_id < 0) {
            throw new IllegalArgumentException("machine_id 必须小于等于31大于0");
        }
        datacenterId = relation_center_id;
        machineId = relation_machine_id;
    }

    private static long getSystemValue(String key) {
        Properties properties = System.getProperties();
        long value;
        if (!StringUtils.isEmpty(System.getenv(key))) {
            value = Long.valueOf(System.getenv(key));
        } else if (!StringUtils.isEmpty(properties.getProperty(key))) {
            value = Long.valueOf(properties.getProperty(key));
        } else {
            throw new IllegalArgumentException("环境变量" + key + "未定义，请在linux系统环境变量或者java启动参数-D添加");
        }
        return value;
    }

    /**
     * 	产生下一个ID
     *
     * @return
     */
    public synchronized long nextId() {
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
 
        if (currStmp == lastStmp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
 
        lastStmp = currStmp;
 
        return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
                | datacenterId << DATACENTER_LEFT       //数据中心部分
                | machineId << MACHINE_LEFT             //机器标识部分
                | sequence;                             //序列号部分
    }
 
    private long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }
 
    private long getNewstmp() {
        return System.currentTimeMillis();
    }
 
}